import {
  Body,
  ClassSerializerInterceptor,
  Controller,
  Get,
  HttpException,
  Post,
  UseFilters,
  UseInterceptors
} from '@nestjs/common'
import { AuthService } from './auth.service'
import { TypeormFilter } from '../filters/typeorm.filter'
import { SigninUserDto } from './dto/signin-user.dto'
// import { SerializeInterceptor } from '../interceptors/serialize/serialize.interceptor'

@Controller('auth')
// 控制器过滤器
// @UseInterceptors(SerializeInterceptor)
@UseFilters(new TypeormFilter())
@UseInterceptors(ClassSerializerInterceptor)
export class AuthController {
  constructor(private AuthService: AuthService) {}
  @Get()
  getTest(): string {
    return 'Hello World!'
  }
  // 登录接口：signin
  @Post('/signin')
  async signin(@Body() dto: SigninUserDto) {
    const { username, password } = dto
    // auth的signin返回token
    const token = await this.AuthService.signin(username, password)
    return {
      access_token: token
    }
  }
  //注册接口

  @Post('signup')
  // 路由拦截器
  // @UseInterceptors(SerializeInterceptor)
  signup(@Body() dto: SigninUserDto) {
    const { username, password } = dto
    //在Controller(控制器)对前端传递过来的数据进行验证，如有管道，则管道会在数据传递到controller之前进行验证
    // if (!username || !password) {
    //   throw new HttpException('用户名或密码不能为空', 400)
    // }
    // if (typeof username !== 'string' || typeof password !== 'string') {
    //   throw new HttpException('用户名或密码格式不正确', 400)
    // }
    // if (
    //   !(typeof username === 'string' && username.length >= 6) ||
    //   !(typeof password === 'string' && password.length >= 6)
    // ) {
    //   throw new HttpException('用户名或密码应为大于或等于6为的字符串', 400)
    // }
    return this.AuthService.signup(username, password)
  }
}
